package com.ripplezjw.blog.interceptor;

import com.ripplezjw.blog.po.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    static final String ROOT_NAME = "Ripple";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();

        if (session == null || session.getAttribute("user_info") == null) {
            // 没有登陆或不是管理员，重定向到login
            request.setAttribute("login_error_msg", "请先登陆");
            // 没法传输数据
//            response.sendRedirect(request.getContextPath() + "login");
            request.getRequestDispatcher("login").forward(request, response);
            return false;
        } else {
            // 已经登陆
//             不是管理员
//            if (!ROOT_NAME.equals(((User)session.getAttribute("user_info")).getUsername())) {
//                response.sendRedirect("index");
//                return false;
//            }
            if (!((User) session.getAttribute("user_info")).isRoot()) {
                response.sendRedirect("/index");
                return false;
            }
            return true;
        }
    }
}
